//
//  HSDSpidermanMonitor.m
//  GoldenCard
//
//  Created by 正合适 on 2018/3/21.
//  Copyright © 2018年 合时代. All rights reserved.
//

/*
 界面记录策略：1、app的打开关闭记录 2、回到开始界面
 */


#import "HSDSpidermanMonitor.h"
#import "Aspects.h"
#import <UIKit/UIKit.h>
#import "HSDSpidermanPageHelper.h"
#import "HSDSpidermanTools.h"

@interface HSDSpidermanMonitor ()

/***/
@property (nonatomic, strong) NSThread *mainThread;
/**页面*/
@property (nonatomic, strong) HSDSpidermanPageHelper *pageHelper;
/**自定义数据*/
@property (nonatomic, strong) NSMutableArray *igonrClassArr;
@end

@implementation HSDSpidermanMonitor

- (instancetype)initWithThread:(NSThread *)thread {
    self = [super init];
    if (self) {
        _mainThread = thread;
        [self index];
    }
    return self;
}

- (void)index {
    _pageHelper = [[HSDSpidermanPageHelper alloc] init];
    _pageHelper.mainThread = _mainThread;
    _igonrClassArr = @[instanceClassName([UINavigationController class]), @"UICompatibilityInputViewController", @"UIInputWindowController"].mutableCopy;
}

#pragma mark - 开启监听
- (void)startMonitor {
    // 页面监听
    [self pageMonitor];
    
    // to do ...
}

#pragma mark - 页面监听
- (void)pageMonitor {
    __weak typeof(self) weakself = self;
    [[UIViewController class] aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
        [weakself actionSelector:@selector(pageEnterMonitorResultAction:) withObject:aspectInfo];
    } error:NULL];
//    [[UIViewController class] aspect_hookSelector:@selector(viewDidDisappear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
//        [weakself actionSelector:@selector(pageLeaveMonitorResultAction:) withObject:aspectInfo];
//    } error:NULL];
}

#pragma mark - 页面进入监听结果
- (void)pageEnterMonitorResultAction:(id<AspectInfo>)aspectInfo {
    if (![HSDSpidermanTools isTopVC:aspectInfo.instance]) return;
    if ([_igonrClassArr containsObject:instanceClassName([aspectInfo.instance class])]){
         return;
    }
    // 把对象换成内存地址
    NSString *memoryAddress = [NSString stringWithFormat:@"%p",aspectInfo.instance];
    NSDictionary *instanceInfo = @{@"address":memoryAddress,@"className":instanceClassName(aspectInfo.instance)};
    [_pageHelper pageEnterWithObject:instanceInfo];
}

#pragma mark - 界面离开的监听结果
- (void)pageLeaveMonitorResultAction:(id<AspectInfo>)aspectInfo {
//    if (![HSDSpidermanTools isTopVC:aspectInfo.instance]) return;
//    if ([_igonrClassArr containsObject:instanceClassName([aspectInfo.instance class])]){
//        return;
//    }
//    [_pageHelper pageLeaveWithObject:aspectInfo.instance];
}

#pragma mark - ---------- 其他 ----------
#pragma mark - 当前线程执行(含参)
- (void)actionSelector:(SEL)selector withObject:(id)object {
    [self performSelector:selector onThread:self.mainThread withObject:object waitUntilDone:YES];
}
#pragma mark - 当前线程执行
- (void)actionSelector:(SEL)selector {
    [self actionSelector:selector withObject:nil];
}

@end
